package com.saftalk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.IOUtils;

import com.google.api.server.spi.IoUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.saftalk.db.PMF;
import com.saftalk.db.entity.User;
import com.saftalk.ui.UIMessageResult;
import com.saftalk.ui.UIPresenceListResult;
import com.saftalk.ui.UIUserResult;

public class InstallServlet extends BaseServlet {

	
	private static final long serialVersionUID = -390419067525928130L;
	User userRet = null;
	
	@SuppressWarnings("unchecked")
	private User getSeniorByFamilyId(long familyId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(User.class);
		List<User> results;
		try {
		q.setFilter("familyId == familyIdParam ");
		q.declareParameters("long familyIdParam");
		results = (List<User>) q.execute(familyId);
		for (User user : results) {
			if (user.isSenior()){
				userRet=user;
			}
		}
		
		
		} finally {
			q.closeAll();
		}
		return userRet;
	}
	
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		/*
		resp.setContentType("application/force-download");
		resp.setHeader("Content-Disposition","attachment; filename=\"" + "saftalkSeniorInstaller.vbs\"");
		*/
		
		
		
		resp.setCharacterEncoding("windows-1255");

		if ("/get".equals(req.getPathInfo())) {
			
			UIUserResult user = (UIUserResult) req.getSession().getAttribute(
					"user");
			if (user == null) {
				resp.getWriter().println("Error! Not logged in.");
				return;						
			}
			
			User seniorUser = getSeniorByFamilyId(user.getFamilyId());;
		
			if (seniorUser==null){
				resp.getWriter().println("Error! No senior user");
				return;
			}
			resp.setContentType("application/force-download");
			resp.setHeader("Content-Disposition","attachment; filename=\"" + "saftalkSeniorInstaller.vbs\"");
			
			ServletContext context = getServletContext();
			InputStream inputStream = context.getResourceAsStream("/WEB-INF/installSaftalk.vbs");
		
			
			String username=seniorUser.getEmail();
			String password= (seniorUser.getGeneratedPassword() == null) ? seniorUser.getPassword() : seniorUser.getGeneratedPassword();
			String name=seniorUser.getName();
			if (password==null || name==null || username==null){
				resp.getWriter().println("Error! missing login details");
				return;
			}
			String finalFile =convertStreamToString(inputStream);
			finalFile=finalFile.replace("#USER_STRING#", username);
			finalFile=finalFile.replace("#PASS_STRING#", password);
			finalFile=finalFile.replace("#NAME_STRING#", name);
		
			
			resp.getWriter().println(finalFile);
		}
	}
	
	public String convertStreamToString(InputStream is) throws IOException {
 
	if (is != null) {
	 Writer writer = new StringWriter();
	 
	            char[] buffer = new char[1024];
	            try {
	                Reader reader = new BufferedReader(
	                        new InputStreamReader(is, "windows-1255"));
	                int n;
	                while ((n = reader.read(buffer)) != -1) {
	                    writer.write(buffer, 0, n);
	                }
	            } finally {
	                is.close();
	            }
	            return writer.toString();
	        } else {        
	            return "";
	        }
	}
}
		
